package com.gopay.scheduler.job;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.Tran01813OpType;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.acct.CommonQueryDAO;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.transfer.Trans01813VO;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.remote.acps.service.AcctTransRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.CallCPSHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * 云账户子账户收款后两笔关联订单做帐定时任务
 * 
 * @Tran01813DoAccountJob.java
 * @author sh.jiao
 * @2017-9-26 上午11:18:35 www.gopay.com.cn Inc.All rights reserved.
 */
public class Tran01813DoAccountJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "comQueryDao")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name = "cpsGeneralMainOrderQueryDAO")
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderQueryDAO;

    @Resource(name = "callCPSHelper")
    private CallCPSHelper callCPSHelper;

    @Resource(name = "acctTransRemoteService")
    AcctTransRemoteService acctTransRemoteService;

    @Override
    public void doJobInternal() {
        try {
            logger.info("开始查询需要做关联订单账务的云账户子账户收款订单!");
            // 1.处理内部资金划转账务
            do00901AccountTrans();
            // 2.处理云账户转账账务
            do01812AccountTrans();

            logger.error("云账户关联订单账务处理任务结束！");
        } catch (Exception e) {
            logger.error("做帐失败！",e);
        }
    }

    private void do01812AccountTrans() {
        //1.查询一分钟前,一天的待处理的记录
        List<Object[]> result = commonQueryDAO.findBySql(buildQuerySql(IntTxnCd._00901.value));
        if(result == null || result.size() == 0){
            logger.info("需要做云账户转账账务的内部资金划转交易结果集为null，定时结束任务。");
            return ;
        }
        logger.info("需要做云账户转账账务的内部资金划转交易记录数 = " + result.size());

        //2.处理结果集
        for(int i = 0; i<result.size();i++){
            Object[] obj = result.get(i);

            CPSResponse response;
            try {
                String gopayOrderId = (String) obj[0];
                CpsGenMainOrder mainOrder = cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,gopayOrderId);
                if(mainOrder == null) {
                    logger.error("流水表记录id="+gopayOrderId+"，对应主订单记录不存在！");
                    // TODO 是否需要修改流水表的状态为失败
                    continue;
                }
                Trans01813VO vo = new Trans01813VO();
                vo.setGopayOrderId(gopayOrderId);
                vo.setOpType(Tran01813OpType.DO_01812_ACCOUNT_TRANS);
                logger.error("处理第【"+(i+1)+"】条记录，调用cps做内部资金划转交易账务，主订单订单号="+gopayOrderId);
                response = callCPSHelper.callByVOTicket(vo);
                if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                    logger.error("------调用cps做内部资金划转交易账务返回异常  response=" + response.getRespCode());
                }
            } catch(Exception e) {
                logger.error("云账户关联订单账务处理任务出现异常！",e);
            }
        }
    }

    private void do00901AccountTrans() {

        //1.查询一分钟前,一天的待处理的记录
        List<Object[]> result = commonQueryDAO.findBySql(buildQuerySql(IntTxnCd._01813.value));
        if(result == null || result.size() == 0){
            logger.info("需要做关联订单账务的云账户子账户收款订单结果集为null，定时结束任务。");
            return ;
        }
        logger.info("需要做关联订单账务的云账户子账户收款订单记录数 = " + result.size());

        //2.处理结果集
        for(int i = 0; i<result.size();i++){
            Object[] obj = result.get(i);

            CPSResponse response;
            try {
                String gopayOrderId = (String) obj[0];
                CpsGenMainOrder mainOrder = cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,gopayOrderId);
                if(mainOrder == null) {
                    logger.error("流水表记录id="+gopayOrderId+"，对应主订单记录不存在！");
                    // TODO 是否需要修改流水表的状态为失败
                    continue;
                }
                Trans01813VO vo = new Trans01813VO();
                vo.setGopayOrderId(gopayOrderId);
                vo.setOpType(Tran01813OpType.DO_00901_ACCOUNT_TRANS);
                logger.error("处理第【"+(i+1)+"】条记录，调用cps做内部资金划转交易账务，主订单订单号="+gopayOrderId);
                response = callCPSHelper.callByVOTicket(vo);
                if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                    logger.error("------调用cps做内部资金划转交易账务返回异常  response=" + response.getRespCode());
                }/* else {
                    Trans01813VO vo1 = new Trans01813VO();
                    vo1.setGopayOrderId(gopayOrderId);
                    vo1.setOpType(Tran01813OpType.DO_01812_ACCOUNT_TRANS);
                    logger.error("处理第【"+(i+1)+"】条记录，调用cps做云账户转账交易账务，主订单订单号="+gopayOrderId);
                    response = callCPSHelper.callByVOTicket(vo1);
                    if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                        logger.error("------调用cps做云账户转账交易账务返回异常  response=" + response.getRespCode());
                    }
                }*/
            } catch(Exception e) {
                logger.error("云账户关联订单账务处理任务出现异常！",e);
            }
        }
    }


    private String buildQuerySql(String gopayIntTxnCd){
        // 起始时间，前一天
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c1= Calendar.getInstance();
        c1.add(Calendar.DAY_OF_MONTH,-1);
        String startDate=sdf.format(c1.getTimeInMillis());

        // 结束时间,一分钟前
        Calendar c2 = Calendar.getInstance();
        c2.add(Calendar.MINUTE,-1);
        String endDate = sdf.format(c2.getTimeInMillis());

        StringBuilder sb = new StringBuilder();
        sb.append("SELECT t.gopay_order_id,t.status ");
        sb.append("  FROM CPS_TRAN_01813_ACCOUNT_DTL T");
        sb.append(" WHERE T.GOPAY_INT_TXN_CD = '").append(gopayIntTxnCd).append("'");
        sb.append("   AND t.status = '00'");
        sb.append("   AND T.CREATE_TS >= TO_TIMESTAMP('").append(startDate).append("', 'yyyy-MM-dd hh24:mi:ss')");
        //sb.append("   AND t.create_ts <= TO_TIMESTAMP('").append(endDate).append("', 'yyyy-MM-dd hh24:mi:ss')");

        return sb.toString();
    }


}
